//  定义项目地址
def root = "/ksv";
def workspace = 'workspace';
def project = "page";
def remote = 'https://gitee.com/wsdchigh/html.git';
def branch = 'dev';
//  需要事先指定好 java maven gradle 环境变量
def workPath = root + "/" + workspace + "/" + project +"/console1";
def gitChange = false;
pipeline {
    agent any

    triggers {
        cron('H/5 * * * *')
    }

    stages {
        stage('检查项目') {
            steps {
                script {
                    //  如果不存在目录则创建目录
                    sh "if [ ! -d ${workPath} ] ; then mkdir -p ${workPath} ; fi; "
                    //  检测git是否存在 不存在则创建
                    def git_ = sh returnStdout: true, script: " cd ${workPath} ; ls -a | grep '.git' | awk '{print \$1}'";
                    echo git_
                    //  如果存在git项目 就不管了
                    if (git_ != null && git_.contains(".git")) {
                        echo "仓库已经存在"
                    } else {
                        echo "仓库不存在"
                        gitChange = true;
                        //  初始化项目
                        sh "cd ${workPath} ; " +
                                " git init ;" +
                                " git remote add origin ${remote} ;" +
                                " git fetch ;" +
                                " git checkout ${branch} ;"
                    }

                    //  生成时间戳   去掉换行符
                    //  version = sh returnStdout: true, script: "date +%N | awk '{print \$1}'";
                    //  version = version.trim();

                    //  版本判断C
                    def originVersion = sh returnStdout: true, script: "cd ${workPath};git reflog | awk '{print \$1}'"
                    sh "cd ${workPath};git pull origin ${branch}"
                    def nowVersion = sh returnStdout: true, script: "cd ${workPath};git reflog | awk '{print \$1}'"

                    echo "之前版本号 ${originVersion} 现在版本号 ${nowVersion}"

                    //  如果版本相同则不再编译 否则需要编译
                    if (originVersion.equals(nowVersion)) {
                        gitChange = false;
                    } else {
                        gitChange = true
                    }

                    if(gitChange){
                        //  编译代码
                        sh "cd ${workPath} ; cnpm install  ; npm run build ; cd /ksv/nginx/html/www; rm -rf console ; sleep 5s; cp -R ${workPath}/console ./"
                    }
                }
            }
        }
    }
}